package org.example.service.impl;

import org.example.mapper.UserMapper;
import org.example.pojo.domain.User;
import org.example.pojo.dto.UserRegistrationDto;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void registerUser(UserRegistrationDto registrationDto) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(registrationDto.getUsername()) != null) {
            throw new RuntimeException("用户已存在");
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(registrationDto.getUsername());
        user.setPassword(registrationDto.getPassword());
        user.setEmail(registrationDto.getEmail());
        user.setPhone(registrationDto.getPhone());
        user.setRole(registrationDto.getRole());
        user.setStatus(1);

        // 保存用户
        userMapper.insertUser(user);
    }

    // 验证用户的登录
    @Override
    public User loginUser(String username, String password, String role) {
        User user = userMapper.findByUsername(username);
        // 校验密码
        if (user == null || !password.equals(user.getPassword())) {
            throw new RuntimeException("用户名或者密码无效！");
        }
        // 如果角色不匹配
        if (!role.equals(user.getRole())) {
            throw new RuntimeException("角色不匹配！");
        }
        return user;
    }
}
